#include "..\..\include\system\keyboard_timeout.h"
#include <stdio.h>
#include <conio.h>

static BOOL g_inputReceived = FALSE; // 输入完成标志

// 按键检测线程函数
static DWORD WINAPI KeyCheckThread(LPVOID lpParam) {
    int timeout = *(int*)lpParam;
    int checkInterval = 100;
    int elapsedTime = 0;

    while (elapsedTime < timeout && !g_inputReceived) {
        int keyPressed = 0;
        for (int vk = 8; vk <= 255; ++vk) {
            if (GetAsyncKeyState(vk) & 0x8000) {
                keyPressed = 1;
                break;
            }
        }
        
        if (keyPressed) {
            Sleep(200);
            if (_kbhit()) {
                g_inputReceived = TRUE;
                break;
            }
        }
        
        Sleep(checkInterval);
        elapsedTime += checkInterval;
    }

    if (!g_inputReceived) {
        printf("\n超时未输入，程序自动退出...\n");
        Sleep(1000);
        ExitProcess(0);
    }
    
    return 0;
}

/**
 * 启动一个定时检测按键的线程
 * @param timeout_ms 超时时间（毫秒）
 * @return 成功返回线程句柄，失败返回NULL
 */
HANDLE StartInputTimeoutThread(int timeout_ms) {
    g_inputReceived = FALSE;
    return CreateThread(NULL, 0, KeyCheckThread, &timeout_ms, 0, NULL);
}
/**
 * 通知输入已完成，停止超时检测
 */
void NotifyInputCompleted(void) {
    g_inputReceived = TRUE;
}

void CleanupInputTimeoutThread(HANDLE threadHandle, DWORD wait_ms) {
    if (threadHandle) {
        WaitForSingleObject(threadHandle, wait_ms);
        CloseHandle(threadHandle);
    }
}